package com.kgw.gatewaybluetooth.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.classic.core.activity.BaseActivity;
import com.classic.core.utils.DoubleClickExitHelper;
import com.classic.core.utils.NetworkUtil;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.core.utils.VersionUpdateUtil;
import com.classic.okhttp.gateway.http.ActionHelp;
import com.classic.okhttp.gateway.http.ObjectCallback;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kgw.gatewaybluetooth.DefaultConsts;
import com.kgw.gatewaybluetooth.GbPreferences;
import com.kgw.gatewaybluetooth.R;
import com.kgw.gatewaybluetooth.bean.CardInfo;
import com.kgw.gatewaybluetooth.bean.CardsBean;
import com.kgw.gatewaybluetooth.bean.SchoolInfo;
import com.kgw.gatewaybluetooth.bean.StudentInfo;
import com.kgw.gatewaybluetooth.bean.VersionInfo;
import com.kgw.gatewaybluetooth.cameraUtils.CameraInterface;
import com.kgw.gatewaybluetooth.cameraUtils.CameraSurfaceView;
import com.kgw.gatewaybluetooth.db.CardDao;
import com.kgw.gatewaybluetooth.db.StudentDao;
import com.kgw.gatewaybluetooth.utils.DisplayUtil;
import com.kgw.gatewaybluetooth.utils.FileUtil;
import com.kgw.gatewaybluetooth.utils.ImageUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * Created by jaydenma on 16/6/25.
 */
public class MainCardActivity extends BaseActivity implements CameraInterface.CamOpenOverCallback, AMapLocationListener {

    private static final String TAG = "jayden";

    private static final String CHARACTERISTIC_UUID_RETURN = "00002902-0000-1000-8000-00805f9b34fb";
    private static final String CH_UUID_Notify = "0000fff2-0000-1000-8000-00805f9b34fb";
    private static final String SERVICE_UUID = "00001910-0000-1000-8000-00805f9b34fb";

    private static final long SCAN_PERIOD = 10000; //10 seconds,扫描时间
    private static final long SEARCH_TIME = 20000; //20 seconds,扫描间隔
    private static final long UPLOAD_TIME = 180000; //180 seconds,上传数据包时间间隔
    private static final long HEART_TIME = 300000; //300 seconds,心跳包上送时间间隔
    private static final long UPLOAD_CARD_TIME = 600000; //600 seconds,离网考勤

    private static final int REQUEST_ENABLE_BT = 2;

    private CameraSurfaceView surfaceView = null;
    private float previewRate = -1f;
    private EditText etCardCode;
    public static String imageString = "";
    private String cardCode;
    private String deviceAddress;
    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;

    private Handler mHandler;
    private BluetoothAdapter mBtAdapter = null;
    private String dataTextBefore = "";
    private String dataTextAfter = "";
    private String uploadData = "";
    private String currentData = "";
    private String macAddresses = "";
    private double mLongitude, mLatitude;
    private Timer timer;
    private Timer timer2;
    private Timer timer3;
    private Timer uploadCardTimer;
    private int isLocateSuccess = 0;


    private TextView tvStudentName;
    private TextView tvClassName;
    private ImageView ivStudentHead;
    private ImageView ivParent1, ivParent2, ivParent3, ivParent4;
    private TextView tvTem, tvDeviceStatus;

    private DoubleClickExitHelper doubleClickExit;
    private SoundPool soundPool, soundPool2;

    private StudentDao dao;
    private CardDao cardDao;
    private String basePath;
    private String timestamp;


    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    public static LocalBroadcastManager localBroadcastManager;


    private String mAddress = "";
    private int isFindDevice = 0;
    private BluetoothDevice mBluetoothDevice = null;
    private BluetoothGatt mBluetoothGatt = null;
    private BluetoothDevice device = null;
    private BluetoothGattCharacteristic mBluetoothGattCharacteristic_Notify = null;
    private long time = 0;
    private int dataCount = 0;

//    private clientThread clientConnectThread = null;
//    private BluetoothSocket socket = null;
//    private BluetoothDevice device = null;
//    private readThread mreadThread = null;

//    private int cardCount = 0;
//    private MainService mService;
//    private Intent bindIntent;

    @Override
    public int getLayoutResId() {
        if (DefaultConsts.DEVICE_TYPE.equals("C")) {
            return R.layout.activity_main;
        } else {
            return R.layout.activity_gate;
        }
    }

    @Override
    public void initData() {
        super.initData();
        if (!StringUtil.isEmpty(GbPreferences.getTimeStamp())) {
            timestamp = GbPreferences.getTimeStamp();
        } else {
            timestamp = "0";
        }
        initBroadcast();
        checkVersion();
        dao = StudentDao.getInstance(activity);
        cardDao = CardDao.getInstance(activity);
//        StudentInfo info = dao.getByCardNo("0009239239");
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(activity, R.raw.card_success, 1);
        soundPool2 = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool2.load(activity, R.raw.card_failed, 1);
        mHandler = new Handler();
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBtAdapter = bluetoothManager.getAdapter();
        if (!mBtAdapter.isEnabled()) { //打开蓝牙设备
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Log.v("BluetoothAdapter", "BluetoothAdapter.ACTION_REQUEST_ENABLE");
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        if (mBtAdapter == null) {
            Toast.makeText(getApplicationContext(), "蓝牙不可用", Toast.LENGTH_LONG).show();
            return;
        }
        deviceAddress = StringUtil.getServiceBlueToothMacAddress(mBtAdapter.getAddress()).toUpperCase();
//        connectBluetoothDevice();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getAllStudents(deviceAddress);
            }
        }).start();

//        service_init();
        new Thread(new Runnable() {
            @Override
            public void run() {
                uploadGpsData();
            }
        }).start();
        doubleClickExit = new DoubleClickExitHelper(this);
        doubleClickExit.setTimeInterval(3000);
        doubleClickExit.setToastContent("再按一次退出应用!");
    }

    private void connectBluetoothDevice() {
//        device = mBtAdapter.getRemoteDevice("0F:03:16:52:30:D8");
//        clientConnectThread = new clientThread();
//        clientConnectThread.start();
        if (mBtAdapter != null) {
            mBluetoothDevice = mBtAdapter.getRemoteDevice(mAddress);
        }
        if (mBluetoothDevice != null) {
            mBluetoothGatt = mBluetoothDevice.connectGatt(this, false, mGattcallback);
        }
    }

    //耳温枪连接回调
    BluetoothGattCallback mGattcallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
//                    Log.e(BluetoothService.this.Tag, "连接成功 ");
                gatt.discoverServices();
                tvDeviceStatus.setText("体温枪已连接");
//                    bool3 = paramAnonymousBluetoothGatt.discoverServices();
//                    Log.e(BluetoothService.this.Tag, "发现服务 ： " + bool3);
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                tvDeviceStatus.setText("体温枪已断开");
            }
//                while (paramAnonymousInt2 != 0)
//                {
//                    boolean bool3;
//                    return;
//                }
//                Log.e(BluetoothService.this.Tag, "断开连接");
//                boolean bool2 = BluetoothService.this.refreshDeviceCache();
//                Log.e("ser", "==断开连接 ；======清除缓存 ： " + bool2);
//                BluetoothService.this.sendBroadCast("ble.disconnect");
//                BluetoothService.this.disconnect();
//                BluetoothService.this.startTimer();
//                return;
//            }
//            Log.e(BluetoothService.this.Tag, "回调异常");
//            boolean bool1 = BluetoothService.this.refreshDeviceCache();
//            Log.e("ser", "==回调异常 ；======清除缓存 ： " + bool1);
//            BluetoothService.this.sendBroadCast("ble.disconnect");
//            BluetoothService.this.disconnect();
//            BluetoothService.this.startTimer();
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                BluetoothGattService bluetoothGattService = gatt.getService(UUID.fromString(SERVICE_UUID));
                mBluetoothGattCharacteristic_Notify = bluetoothGattService.getCharacteristic(UUID.fromString(CH_UUID_Notify));
//                BluetoothService.access$302(BluetoothService.this, localBluetoothGattService.getCharacteristic(UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb")));
                if ((0x10 & mBluetoothGattCharacteristic_Notify.getProperties()) > 0) {
                    Log.e("Ble", "具有通知属性。。。");
                    mBluetoothGatt.setCharacteristicNotification(mBluetoothGattCharacteristic_Notify, true);
                    BluetoothGattDescriptor bluetoothGattDescriptor = mBluetoothGattCharacteristic_Notify.getDescriptor(UUID.fromString(CHARACTERISTIC_UUID_RETURN));
                    if (bluetoothGattDescriptor != null) {
                        bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        Log.e("Ble", mBluetoothGattCharacteristic_Notify.getUuid() + "激活通知属性： " + mBluetoothGatt.writeDescriptor(bluetoothGattDescriptor));
                    }
                }
            }
        }


        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic
                characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            if (dataCount == 0) {
                time = System.currentTimeMillis();
            }
            Log.e("Main", StringUtil.Bytes2HexString(characteristic.getValue()));
            dataCount++;
            byte[] tem = characteristic.getValue();
            Log.e("main", Arrays.toString(tem));
            int a, b;
            if (tem[5] != -18) {
                a = ((int) tem[5] & 0xff) << 8;
                b = tem[6] & 0xff;
            } else {
                a = 0;
                b = 0;
            }
            if (dataCount == 10 || System.currentTimeMillis() - time > 3000) {
                time = System.currentTimeMillis();
                String bodyTem = (a + b) + "";
                final String currentTem = bodyTem.substring(0, 2) + "." + bodyTem.charAt(2);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTem.setText(currentTem + "℃");
                    }
                });
                uploadTemperature(currentTem);
                Log.e("main", currentTem);
            }
        }
    };

    private void initBroadcast() {
        intentFilter = new IntentFilter("com.kgw.gateway.LOCALBROADCAST");
        localReceiver = new LocalReceiver();
        //获取实例
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        //注册本地广播监听器
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);
    }


    private void getAllStudents(String deviceAddress) {
        ActionHelp.gbGetAllStudents(activity, deviceAddress, timestamp, new ObjectCallback<SchoolInfo>() {
            @Override
            public void onError(int code) {

            }

            @Override
            public void onSuccess(SchoolInfo response) {
//                ToastUtil.showToast(activity, "数据插入数据库");
                GbPreferences.saveTimeStamp(response.getTimestamp());
                basePath = response.getBasePath();
                if (response.getChildrenList().size() > 0) {
                    putDataToDB(response.getChildrenList());
                }
                if (response.getTeacherList().size() > 0) {
                    putTeacherDataToDB(response.getTeacherList());
                }
//                dao.addList(response.getChildrenList());
            }

            @Override
            public Type getType() {
                return new TypeToken<SchoolInfo>() {
                }.getType();
            }
        });
    }

    private void putTeacherDataToDB(List<StudentInfo> teacherList) {
        for (StudentInfo student : teacherList) {
            if (dao.getByTeacherId(student.getTeacherId()) != null) {
                dao.update(student);
            } else {
                dao.add(student);
            }
        }

        for (StudentInfo student : teacherList) {
            saveImage(basePath + student.getImagePath(), student.getTeacherId() + "T");
            String[] parentsImg = student.getParentPath().split(";");
            if (!StringUtil.isEmpty(parentsImg[0])) {
                int i = 0;
                for (String path : parentsImg) {
                    File file = new File(student.getId() + "_" + i);
                    if (file.isFile() && file.exists()) {
                        file.delete();
                    }
                    saveImage(basePath + path, student.getId() + "_" + i);
                    i++;
                }
            }
        }

    }

    private void putDataToDB(List<StudentInfo> childrenList) {
        for (StudentInfo student : childrenList) {
            if (dao.getById(student.getId()) != null) {
                dao.update(student);
            } else {
                dao.add(student);
            }
        }
        for (StudentInfo student : childrenList) {
            saveImage(basePath + student.getImagePath(), student.getId());
            String[] parentsImg = student.getParentPath().split(";");
            if (!StringUtil.isEmpty(parentsImg[0])) {
                int i = 0;
                for (String path : parentsImg) {
                    File file = new File(student.getId() + "_" + i);
                    if (file.isFile() && file.exists()) {
                        file.delete();
                    }
                    saveImage(basePath + path, student.getId() + "_" + i);
                    i++;
                }
            }
        }
    }


    private void saveImage(String path, final String fileName) {
        ImageLoader.getInstance().loadImage(path, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
                super.onLoadingComplete(imageUri, view, loadedImage);
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FileUtil.saveBitmap(loadedImage, fileName);
                    }
                });
                thread.start();
            }
        });
    }

    private void uploadGpsData() {
        Locate();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                uploadData = "7E" + deviceAddress;
                dataTextBefore = "";
                dataTextAfter = "7E" + deviceAddress + "\n";
                macAddresses = deviceAddress;
                currentData = "";
                scanLeDevice(true);
            }
        }, 0, SEARCH_TIME);

        timer2 = new Timer();
        timer2.schedule(new TimerTask() {
            @Override
            public void run() {
                //上传数据包
                uploadAllData();
            }
        }, SCAN_PERIOD + 2000, UPLOAD_TIME);
        timer3 = new Timer();
        timer3.schedule(new TimerTask() {
            @Override
            public void run() {
                //上传数据包
                uploadHeart();
            }
        }, 0, HEART_TIME);
        uploadCardTimer = new Timer();
        uploadCardTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                //上传离网考勤数据
                if (NetworkUtil.isNetworkAvailable(activity)) {
                    List<CardInfo> dbCards = cardDao.getAll();
                    if (dbCards != null) {
                        uploadOffLineCardData(dbCards);
                    }
                }
            }
        }, 0, UPLOAD_CARD_TIME);
    }

    @Override
    public void initView() {
        super.initView();
        tvStudentName = (TextView) findViewById(R.id.tv_student_name);
        tvClassName = (TextView) findViewById(R.id.tv_class_name);
        ivStudentHead = (ImageView) findViewById(R.id.iv_student_head);
        ivParent1 = (ImageView) findViewById(R.id.iv_parent1);
        ivParent2 = (ImageView) findViewById(R.id.iv_parent2);
        ivParent3 = (ImageView) findViewById(R.id.iv_parent3);
        ivParent4 = (ImageView) findViewById(R.id.iv_parent4);
        tvTem = (TextView) findViewById(R.id.tv_tem);
        tvDeviceStatus = (TextView) findViewById(R.id.tv_device_status);
        surfaceView = (CameraSurfaceView) findViewById(R.id.sv_camera);
        etCardCode = (EditText) findViewById(R.id.et_card_code);
        initViewParams();
        Thread openThread = new Thread() {
            @Override
            public void run() {
                CameraInterface.getInstance().doOpenCamera(MainCardActivity.this, activity);
            }
        };
        openThread.start();
        etCardCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = etCardCode.getText().toString().trim();
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    if (code.length() == 10) {
                        cardCode = code;
                        etCardCode.setText("");
//                        cardCount++;
                        CameraInterface.getInstance().doTakePicture();
                    } else {
                        if (code.length() > 0) {
//                            soundPool2.load(activity,R.raw.card_failed,1);
                            soundPool2.play(1, 15, 15, 0, 0, 1);
                            ToastUtil.showToast(activity, "刷卡失败,请重新刷卡");
                            etCardCode.setText("");
                        }
                    }
                    return true;
                }
                return false;
            }
        });
//        etCardCode.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                String code = etCardCode.getText().toString().trim();
//                if (code.length() == 10) {
//                    CameraInterface.getInstance().doTakePicture();
//                    cardCode = code;
//                    etCardCode.setText("");
//                    Timer timer = new Timer();
//                    timer.schedule(new TimerTask() {
//                        @Override
//                        public void run() {
//                            uploadCardData();
//                        }
//                    }, 200);
//                }
//            }
//        });
    }

    private void uploadOffLineCardData(List<CardInfo> dbCards) {
        Log.e("jayden", "上传");
        List<CardInfo> cards = new ArrayList<CardInfo>();
        for (CardInfo card : dbCards) {
            CardInfo c = new CardInfo();
            c.setCardNo(card.getCardNo());
            c.setImagePath(card.getImagePath());
            c.setTimestamp(card.getTimestamp());
            cards.add(c);
        }
        CardsBean bean = new CardsBean();
        bean.setReturnObject(cards);
        bean.setDeviceAddress(deviceAddress);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(bean);
        Log.e("jayden", jsonStr);
        ActionHelp.gbUploadCardData(activity, jsonStr, new ObjectCallback<String>() {
            @Override
            public void onError(int code) {
//                soundPool2.load(activity,R.raw.card_failed,1);
                Log.e("jayden", code + "");
            }

            @Override
            public void onSuccess(String response) {
                ToastUtil.showToast(activity, "离网信息上传成功");
                cardDao.deleteAll();
//                StudentInfo info = dao.getByCardNo(cardCode);
//                updateStudentInfo(info);
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void uploadCardData() {
        Log.e("jayden", "上传");
        String timeStamp = new Date().getTime() + "";
        CardsBean bean = new CardsBean();
        CardInfo card = new CardInfo();
        List<CardInfo> cards = new ArrayList<CardInfo>();
        card.setCardNo(cardCode);
        card.setImagePath(imageString + "#jpg");
        card.setTimestamp(timeStamp);
        cards.add(card);
        bean.setReturnObject(cards);
        bean.setDeviceAddress(deviceAddress);
        Gson gson = new Gson();
        String jsonStr = gson.toJson(bean);
        Log.e("jayden", jsonStr);
        ActionHelp.gbUploadCardData(activity, jsonStr, new ObjectCallback<String>() {
            @Override
            public void onError(int code) {
//                soundPool2.load(activity,R.raw.card_failed,1);
                soundPool2.play(1, 15, 15, 0, 0, 1);
                Log.e("jayden", code + "");
            }

            @Override
            public void onSuccess(String response) {
                ToastUtil.showToast(activity, "刷卡信息上传成功");
                soundPool.play(1, 15, 15, 0, 0, 1);
//                StudentInfo info = dao.getByCardNo(cardCode);
//                updateStudentInfo(info);
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void updateStudentInfo(StudentInfo response) {
        if (response != null) {
            String[] parentsImg = response.getParentPath().split(";");
//            Log.e("jayden",response.getChildrenId());
            Log.e("jayden", response.getId());
            tvStudentName.setText("姓名:" + (StringUtil.isEmpty(response.getNAME()) ? response.getChildrenName() : response.getNAME()));
            tvClassName.setText("班级:" + response.getClassname());
            if (!StringUtil.isEmpty(response.getImagePath())) {
//                Picasso.with(activity).load(FileUtil.getPath() + "/" + response.getId() + ".jpg").fit().into(ivStudentHead);
                Log.e("jayden", FileUtil.getPath() + "/" + response.getId() + ".jpg");
                if (StringUtil.isEmpty(response.getNAME())) {
                    ivStudentHead.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + ".jpg"));
                } else {
                    ivStudentHead.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getTeacherId() + "T.jpg"));
                }
            } else {
                Picasso.with(activity).load(R.mipmap.head_img).fit().into(ivStudentHead);
            }
            if (parentsImg.length > 3) {
                ivParent1.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_0.jpg"));
                ivParent2.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_1.jpg"));
                ivParent3.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_2.jpg"));
                ivParent4.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_3.jpg"));
            } else if (parentsImg.length > 2) {
                ivParent1.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_0.jpg"));
                ivParent2.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_1.jpg"));
                ivParent3.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_2.jpg"));
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent4);
            } else if (parentsImg.length > 1) {
                ivParent1.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_0.jpg"));
                ivParent2.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_1.jpg"));
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent3);
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent4);
            } else if (parentsImg.length > 0) {
                ivParent1.setImageBitmap(ImageUtil.getLoacalBitmap(FileUtil.getPath() + "/" + response.getId() + "_0.jpg"));
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent2);
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent3);
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent4);
            } else {
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent1);
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent2);
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent3);
                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent4);
            }
//            if (!StringUtil.isEmpty(response.getImagePath())) {
//                Picasso.with(activity).load(basePath + response.getImagePath()).fit().into(ivStudentHead);
//            } else {
//                Picasso.with(activity).load(R.mipmap.head_img).fit().into(ivStudentHead);
//            }
//            if (!StringUtil.isEmpty(parentsImg[0])) {
//                Picasso.with(activity).load(basePath + parentsImg[0]).fit().into(ivParent1);
//            } else {
//                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent1);
//            }
//            if (parentsImg.length > 1) {
//                Picasso.with(activity).load(basePath + parentsImg[1]).fit().into(ivParent2);
//            } else {
//                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent2);
//            }
//            if (parentsImg.length > 2) {
//                Picasso.with(activity).load(basePath + parentsImg[2]).fit().into(ivParent3);
//            } else {
//                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent3);
//            }
//            if (parentsImg.length > 3) {
//                Picasso.with(activity).load(basePath + parentsImg[3]).fit().into(ivParent4);
//            } else {
//                Picasso.with(activity).load(R.mipmap.ic_launcher).fit().into(ivParent4);
//            }
//            cardCount = 0;
            if (NetworkUtil.isNetworkAvailable(activity)) {
                uploadCardData();
            } else {
                //没有网络,数据存入数据库
                soundPool.play(1, 15, 15, 0, 0, 1);
                String timeStamp = new Date().getTime() + "";
                CardInfo card = new CardInfo();
                card.setCardNo(cardCode);
                card.setImagePath(imageString + "#jpg");
                card.setTimestamp(timeStamp);
                cardDao.add(card);
            }
        } else {
            soundPool2.play(1, 15, 15, 0, 0, 1);
        }
    }

    private void initViewParams() {
        ViewGroup.LayoutParams params = surfaceView.getLayoutParams();
        Point p = DisplayUtil.getScreenMetrics(this);
//        params.width = p.x / 3 - 50;
        if (DefaultConsts.DEVICE_TYPE.equals("C")) {
            params.width = 400;
            params.height = 270;
        } else {
            params.width = 800;
            params.height = 560;
        }
        previewRate = DisplayUtil.getScreenRate(this); //默认全屏的比例预览
        surfaceView.setLayoutParams(params);

    }


    @Override
    public void cameraHasOpened() {
        SurfaceHolder holder = surfaceView.getSurfaceHolder();
        CameraInterface.getInstance().doStartPreview(holder, previewRate);
    }

    public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
        return this.doubleClickExit.onKeyDown(paramInt, paramKeyEvent);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        isLocateSuccess = 1;
//        tvLongitude.setText("经度: " + aMapLocation.getLongitude());
//        tvLatitude.setText("纬度: " + aMapLocation.getLatitude());
        mLongitude = aMapLocation.getLongitude();
        mLatitude = aMapLocation.getLatitude();
    }


    private void uploadHeart() {
        ActionHelp.gbGetCarData(activity, mLongitude, mLatitude, deviceAddress, "M", new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response) {
//                ToastUtil.showToast(activity, "上传成功");
            }

            @Override
            public void onError(int code) {
                ToastUtil.showToast(getApplicationContext(), "上传失败");
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void uploadAllData() {
        if (isLocateSuccess == 0) return;
        ActionHelp.gbGetCarData(activity, mLongitude, mLatitude, currentData, "D", new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response) {
//                ToastUtil.showToast(activity, "上传成功");
            }

            @Override
            public void onError(int code) {
                ToastUtil.showToast(getApplicationContext(), "上传失败");
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void Locate() {
        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(10000);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
    }

    private void scanLeDevice(boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBtAdapter.stopLeScan(mLeScanCallback);
                    currentData = uploadData;
                    Log.v("bletooth", "mBluetoothAdapter.stopLeScan");
                    //上传数据
                    uploadOnlyMacAddress();
                    if (isFindDevice == 1) {
                        isFindDevice = 0;
                        connectBluetoothDevice();
                    }
                }
            }, SCAN_PERIOD);
            mBtAdapter.startLeScan(mLeScanCallback);
            Log.v("bletooth", "mBluetoothAdapter.startLeScan");
        } else {
            mBtAdapter.stopLeScan(mLeScanCallback);
        }
    }

    private void uploadOnlyMacAddress() {
        if (isLocateSuccess == 0) return;
        ActionHelp.gbGetCarData(activity, mLongitude, mLatitude, macAddresses, "G", new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response) {
//                ToastUtil.showToast(activity, "上传成功");
            }

            @Override
            public void onError(int code) {
                ToastUtil.showToast(getApplicationContext(), "上传失败");
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                    if (!StringUtil.isEmpty(device.getName())) {
                        if (device.getName().equals("FSRKB-EWQ01")) {
                            isFindDevice = 1;
                            mAddress = device.getAddress();
                        }
                    }
                    //收集数据
                    if (macAddresses.indexOf(StringUtil.getServiceBlueToothMacAddress(device.getAddress())) == -1) {
                        macAddresses = macAddresses + StringUtil.getServiceBlueToothMacAddress(device.getAddress());
                        dataTextBefore = dataTextBefore + StringUtil.Bytes2HexString(scanRecord) + "\n";
//                        tvDataBefore.setText(dataTextBefore);
                        String temp = "1EFF7E" + StringUtil.Bytes2HexStringNoX(scanRecord).substring(8, 42);
                        uploadData = uploadData + temp;
                        dataTextAfter = dataTextAfter + temp + "\n";
//                        tvDataAfter.setText(dataTextAfter);
                    }
                    Log.e("data", uploadData);
                    Log.e("macAddress", macAddresses);
                }
            };


    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public int getVersionCode() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            int versionCode = info.versionCode;
            return versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    private void checkVersion() {
        ActionHelp.gbVersion(this, new ObjectCallback<VersionInfo>() {
            @Override
            public void onError(int code) {
                ToastUtil.showToast(activity, "获取版本失败");
            }

            @Override
            public void onSuccess(VersionInfo response) {
                if (response != null) {
                    int newVersionCode = Integer.parseInt(response.getVERSIONNUM());
                    if (newVersionCode > getVersionCode()) {
                        if (Environment.getExternalStorageState().equals(
                                Environment.MEDIA_MOUNTED)) {
                            String url = response.getPATH();
                            VersionUpdateUtil util = new VersionUpdateUtil();
                            util.downFile(url, MainCardActivity.this);
                        } else {
                            Toast.makeText(MainCardActivity.this, "SD卡不可用，请插入SD卡",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<VersionInfo>() {
                }.getType();
            }
        });
    }

//    public static String byte2hex(byte[] b) { //一个字节的数，
//
//        // 转成16进制字符串
//
//        String hs = "";
//        String tmp = "";
//        for (int n = 0; n < b.length; n++) {
//            //整数转成十六进制表示
//
//            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
//            if (tmp.length() == 1) {
//                hs = hs + "0" + tmp;
//            } else {
//                hs = hs + tmp;
//            }
//        }
//        tmp = null;
//        return hs.toUpperCase(); //转成大写
//
//    }


    //读取数据
//    private class readThread extends Thread {
//        public void run() {
//
//            byte[] buffer = new byte[1024];
//            int bytes;
//            InputStream mmInStream = null;
//
//            try {
//                mmInStream = socket.getInputStream();
//            } catch (IOException e1) {
//                // TODO Auto-generated catch block
//                e1.printStackTrace();
//            }
//            while (true) {
//                try {
//                    // Read from the InputStream
//                    if ((bytes = mmInStream.read(buffer)) > 0) {
//                        byte[] buf_data = new byte[bytes];
//                        for (int i = 0; i < bytes; i++) {
//                            buf_data[i] = buffer[i];
//                        }
//                        String s = new String(byte2hex(buf_data));
//                        final String tem = Integer.valueOf(s.substring(2, 6), 16).toString();
//                        final String currentTem = tem.substring(0, 2) + "." + tem.charAt(2) + "℃";
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                tvTem.setText(currentTem);
//                            }
//                        });
//                        uploadTemperature(currentTem);
//                    }
//                } catch (IOException e) {
//                    try {
//                        mmInStream.close();
//                    } catch (IOException e1) {
//                        // TODO Auto-generated catch block
//                        e1.printStackTrace();
//                    }
//                    break;
//                }
//            }
//        }
//    }

    private void uploadTemperature(String currentTem) {
        dataCount = 0;
        if (!StringUtil.isEmpty(cardCode)) {
            ActionHelp.gbUploadTemperature(activity, cardCode, currentTem, new ObjectCallback<String>() {
                @Override
                public void onSuccess(String response) {
                    ToastUtil.showToast(activity, "体温上传成功");
                }

                @Override
                public void onError(int code) {
                    Log.e("main", code + "");
                }

                @Override
                public Type getType() {
                    return new TypeToken<String>() {
                    }.getType();
                }
            });
        }
    }


    //开启客户端
//    private class clientThread extends Thread {
//        public void run() {
//            try {
//                //创建一个Socket连接：只需要服务器在注册时的UUID号
//                socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//                socket.connect();
//                mreadThread = new readThread();
//                mreadThread.start();
//            } catch (IOException e) {
//                Log.e("connect", "", e);
//            }
//        }
//    }


    //定义广播接收器
    public class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            imageString = arg1.getStringExtra("data");
//            if (NetworkUtil.isNetworkAvailable(activity)) {
            Log.e("jayden", "拍照成功");
//            if (cardCount == 1) {
            StudentInfo info = dao.getByCardNo(cardCode);
            updateStudentInfo(info);
//            }
//            } else {
//                //没有网络,打卡信息存入本地数据库
//
//            }
        }


    }
}